package com.lhl.security.filter;

import com.alibaba.fastjson.JSONObject;
import com.lhl.security.domain.Menu;
import com.lhl.security.domain.Role;
import com.lhl.security.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class UserRightsFilter implements FilterInvocationSecurityMetadataSource {
    AntPathMatcher antPathMatcher = new AntPathMatcher();

    private final MenuService menuService;

    public UserRightsFilter(MenuService menuService) {
        this.menuService = menuService;
    }

    /**
     * 通过 来找到当前访问路径在在数据库对应的路径访问需要的角色
     *
     * @param object
     * @return
     * @throws IllegalArgumentException
     */
    // 判断请求路径需要那些角色可以访问
    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        //获取请求地址
        String requestUrl = ((FilterInvocation) object).getRequestUrl();
        //判断是不是登录权限
        if (antPathMatcher.matchStart("/user/login", requestUrl) ||
                antPathMatcher.matchStart("/wechat/login", requestUrl)) {
            return SecurityConfig.createList("ROLE_LOGIN");
        }
        //获取所有权限路径
        List<Menu> menuList = menuService.getAllMenuList();
        for (Menu menu : menuList) {
            //通过方法找到数据库和当前路径对应的一条信息
            if (antPathMatcher.matchStart(menu.getUrl(), requestUrl)) {
                List<Role> roles = menu.getRoles();
                //把当前路径对应的角色添加到数组中返回
                String[] roleStrs = roles.stream().map(Role::getName).toArray(String[]::new);
                System.out.println(JSONObject.toJSONString(roleStrs));
                return SecurityConfig.createList(roleStrs);
            }
        }
        // 对于没有匹配到的一些请求地址，默认其登录后就可以访问
        return SecurityConfig.createList("ROLE_LOGIN");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }
}

